﻿(function () {
    'use strict';

    var map = null;
    var mapCredentials = "AtdEdzGw6hwYDfHOU_un_NIssCc1gdEdBy3bXpmnAFqoNkszL83o6qTeLM04j3b0";

    var homeLoc = null;
    var homePushpin = null;
    getMap()
    function getMap() {
        var mapOptions = {
            credentials: mapCredentials
        }
        function initMap() { 
            var s = document.querySelector(".mapDiv");
            map = new Microsoft.Maps.Map(s, mapOptions);
            Microsoft.Maps.loadModule('Microsoft.Maps.VenueMaps', { callback: venuemapsModuleLoaded });

            function venuemapsModuleLoaded() {

                // Create the venue map
                var vmaps = new Microsoft.Maps.VenueMaps.VenueMapFactory(map);

                vmaps.create({ venueMapId: 'hcl-cornelluniversity', success: SetVenue });


            }

            function SetVenue(venueObj) {
                venue = venueObj;
                ShowVenue();
            }

            function ShowVenue() {
                // Set the map view 
                map.setView(venue.bestMapView);
                venue.show();
            }

        };



    }

    function listenForMessages() {
        window.addEventListener("message", onGetMessage, false);
    }

    function parseResponse(responseText) {
        var responseObj = JSON.parse(responseText);
        return responseObj;
    }

    function setHomeLoc(loc) {
        var lat = parseFloat(loc.Latitude);
        var longitude = parseFloat(loc.Longitude);
        homeLoc = new Microsoft.Maps.Location(lat, longitude);
        if (!homePushpin) {
            homePushpin = new Microsoft.Maps.Pushpin(homeLoc, { draggable: false });
            map.entities.push(homePushpin);
        }
        else {
            homePushpin.setLocation(homeLoc);
        }
    }

    function recenter(currentLoc) {
        var lat = parseFloat(currentLoc.Latitude);
        var longitude = parseFloat(currentLoc.Longitude);
        map.setView({ center: new Microsoft.Maps.Location(lat, longitude) });
    }

    function setZoom(num) {
        map.setView({ zoom: num });
    }

    function onGetMessage(e) {
        var responseObj = parseResponse(e.data);
        if (responseObj.messageType == "PhotoLocation") {
            setHomeLoc(responseObj);
            recenter(responseObj);
            setZoom(8);
        }
    }

    window.onload = function () {
        listenForMessages();
        getMap();
    }

})();
